package com.shqcjd.sinopecdemomobile.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.support.v7.widget.GridLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.eventbus.GoGuideEvent;
import com.shqcjd.sinopecdemomobile.model.eventbus.IndexAllEvent;
import com.shqcjd.sinopecdemomobile.model.pojo.IndexBean;
import com.shqcjd.sinopecdemomobile.model.pojo.MenuEntity;
import com.shqcjd.sinopecdemomobile.ui.activity.DefectManageActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.EquipmentInfoActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.ExpertDetailActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.ExpertListActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.HeadlineNewsActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.IntellectInspectActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.KnowledgeInfoActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.MessageListActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.NewsDetailActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.TrajectoryActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.count.FormActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.count.LeafSortActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.maintain.MaintainListActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.problem.ProblemFeedbackActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.problem.ProblemListActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.ProcessBackActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.QRcodeActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.tipwizard.TipWizardListActivity;
import com.shqcjd.sinopecdemomobile.ui.adapter.BannerImageLoader;
import com.shqcjd.sinopecdemomobile.ui.adapter.HeadlinesAdapter;
import com.shqcjd.sinopecdemomobile.ui.adapter.HorizontalExpertAdapter;
import com.shqcjd.sinopecdemomobile.ui.adapter.KnowledgeBaseAdapter;
import com.shqcjd.sinopecdemomobile.ui.adapter.MenuAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseFragment;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.SpacesItemDecoration;
import com.shqcjd.sinopecdemomobile.util.ToastUtils;
import com.shqcjd.sinopecdemomobile.util.UIUtils;
import com.shqcjd.sinopecdemomobile.widget.ScaleCircleView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

import static android.app.Activity.RESULT_OK;

/**
 * 首页
 * Created by sy on 2019/3/14.
 */

public class HomeFragment extends BaseFragment {
    private static final int REQUEST_CODE = 1000;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.rv_menu_list)
    RecyclerView rv_menu_list;
    @BindView(R.id.rv_headlines)
    RecyclerView rv_headlines;
    @BindView(R.id.rv_expert)
    RecyclerView rv_expert;
    @BindView(R.id.tv_more_news)
    TextView tvMoreNews;
    @BindView(R.id.tv_more_expert)
    TextView tvMoreExpert;
    @BindView(R.id.iv_news)
    ImageView iv_news;
    @BindView(R.id.iv_scan)
    ImageView iv_scan;
    @BindView(R.id.ll_news_layout)
    LinearLayout ll_news_layout;
    @BindView(R.id.ll_chart_layout)
    LinearLayout ll_chart_layout;
    @BindView(R.id.ll_expert_layout)
    LinearLayout ll_expert_layout;
    @BindView(R.id.iv_reddot)
    ImageView iv_reddot;
    @BindView(R.id.ll_search)
    LinearLayout ll_search;
    @BindView(R.id.rv_knowledge_base)
    RecyclerView rv_knowledge_base;
    @BindView(R.id.ll_expert_btn)
    LinearLayout ll_expert_btn;
    @BindView(R.id.ll_inspection_btn)
    LinearLayout ll_inspection_btn;
    @BindView(R.id.ll_guide_btn)
    LinearLayout ll_guide_btn;
    @BindView(R.id.ll_knowledge_base_layout)
    LinearLayout ll_knowledge_base_layout;
    @BindView(R.id.ll_tools)
    LinearLayout ll_tools;
    @BindView(R.id.scv_answer)
    ScaleCircleView scv_answer;
    @BindView(R.id.tv_answer)
    TextView tv_answer;
    @BindView(R.id.scv_satisfi)
    ScaleCircleView scv_satisfi;
    @BindView(R.id.tv_satisfi)
    TextView tv_satisfi;
    @BindView(R.id.scv_support)
    ScaleCircleView scv_support;
    @BindView(R.id.tv_support)
    TextView tv_support;
    @BindView(R.id.ll_gadget_form)
    LinearLayout ll_gadget_form;
    @BindView(R.id.ll_gadget_leaf)
    LinearLayout ll_gadget_leaf;

    private List<String> mMenuList;

    List<MenuEntity> mMenuEntityList = new ArrayList<>();
    static final Integer[] iconimgs = new Integer[]{
            R.mipmap.xjxt, R.mipmap.qxgl, R.mipmap.yczd, R.mipmap.txhf, R.mipmap.sbgl};
    private MenuAdapter menuAdapter;



    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_home;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }


    @Override
    public void initView(View rootView) {
        EventBus.getDefault().register(this);//订阅
        //轮播图
        initBanner();

        //顶部菜单列表
        initMenu();

    }

    @Override
    public void initData() {
    }

    /**
     * 专家指导
     * @param expert
     */
    private void initExpert(List<IndexBean.ExpertBean> expert) {
        HorizontalExpertAdapter horizontalExpertAdapter = new HorizontalExpertAdapter(expert);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        rv_expert.setLayoutManager(linearLayoutManager);
        rv_expert.setAdapter(horizontalExpertAdapter);
        //添加ItemDecoration，item之间的间隔
        int leftRight = UIUtils.dip2px(3);
        int topBottom = UIUtils.dip2px(0);
        int padding = UIUtils.dip2px(10);
        rv_expert.addItemDecoration(new SpacesItemDecoration(leftRight, topBottom, true, padding));
        horizontalExpertAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                IndexBean.ExpertBean item = (IndexBean.ExpertBean) adapter.getItem(position);
                Intent intent = new Intent(getContext(), ExpertDetailActivity.class);
                intent.putExtra("ExpertId", item.id);
                startActivity(intent);
            }
        });


    }


    /**
     * 显示满意度统计图表
     * @param satisfaction
     */
    private void initChart(List<IndexBean.SatisfactionBean> satisfaction) {

        for (IndexBean.SatisfactionBean bean : satisfaction) {
            int ratio = (int) Math.ceil(bean.rate / 10);
            switch (bean.label) {
                case "问题答复率":
                    scv_answer.setSelect(ratio);
                    tv_answer.setText(bean.rate+"%");
                    break;
                case "知识库满意率":
                    scv_satisfi.setSelect(ratio);
                    tv_satisfi.setText(bean.rate+"%");
                    break;
                case "专家支持率":
                    scv_support.setSelect(ratio);
                    tv_support.setText(bean.rate+"%");
                    break;
            }
        }
    }


    /**
     * 头条新闻
     * @param news
     */
    private void initHeadlines(List<IndexBean.NewsBean> news) {
        HeadlinesAdapter headlinesAdapter = new HeadlinesAdapter(news);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        rv_headlines.setLayoutManager(linearLayoutManager);
        rv_headlines.setAdapter(headlinesAdapter);
        //添加ItemDecoration，item之间的间隔
        int leftRight = UIUtils.dip2px(10);
        int topBottom = UIUtils.dip2px(0);
        rv_headlines.addItemDecoration(new SpacesItemDecoration(leftRight, topBottom));
        headlinesAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                IndexBean.NewsBean item = (IndexBean.NewsBean) adapter.getItem(position);
                Intent intent = new Intent(getContext(), NewsDetailActivity.class);
                intent.putExtra("newsId", item.id);
                startActivity(intent);
            }
        });
    }

    /**
     *  判断集合是否包含某属性
     * @return
     */
    private Boolean isContains(String string, List<MenuEntity> list) {
        for (MenuEntity bean : list) {
            if (bean.name.equals(string)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 菜单列表
     * @param
     */
    private void initMenu() {
        mMenuList = Arrays.asList(getResources().getStringArray(R.array.home_menu));
        mMenuEntityList.clear();
//        for (int i = 0; i < childs.size(); i++) {
//            MenuEntity mMenuBean = new MenuEntity();
//            mMenuBean.url = childs.get(i).current.icon;
//            mMenuBean.name = childs.get(i).current.menu_name;
//
//            mMenuEntityList.add(mMenuBean);
//        }
        for (int i = 0; i < mMenuList.size(); i++) {
            MenuEntity mMenuBean = new MenuEntity();
            mMenuBean.name = mMenuList.get(i);
            mMenuEntityList.add(mMenuBean);
        }


        //判断是否显示巡检模块
//        if (isContains("巡检系统",mMenuEntityList)) {
//            EventBus.getDefault().post(new ShowInspectionEvnent(true));
//        } else {
//            EventBus.getDefault().post(new ShowInspectionEvnent(false));
//        }
//
//        //判断app是否显示专家模块
//        if (isContains("远程指导",mMenuEntityList)) {
//            EventBus.getDefault().post(new ShowGuideEvent(true));
//        } else {
//            EventBus.getDefault().post(new ShowGuideEvent(false));
//        }

        //布局管理器对象 参数1.上下文 2.规定一行显示几列的参数常量
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), mMenuList.size());
        //设置RecycleView显示的方向是水平还是垂直 GridLayout.HORIZONTAL水平  GridLayout.VERTICAL默认垂直
        gridLayoutManager.setOrientation(GridLayout.VERTICAL);
        rv_menu_list.setLayoutManager(gridLayoutManager);
        menuAdapter = new MenuAdapter(mMenuEntityList);
        rv_menu_list.setAdapter(menuAdapter);
        menuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MenuEntity menuEntity = (MenuEntity) adapter.getData().get(position);
                Intent it;
                //根据点击不同菜单跳转
                switch (menuEntity.name) {
                    case "问题反馈":
                        it = new Intent(getActivity(),ProblemListActivity.class);
                        startActivity(it);
                        break;
                    case "智能维修":
                        it= new Intent(getActivity(), MaintainListActivity.class);
                        startActivity(it);
                        break;
                    case "图像回放":
                        it= new Intent(getActivity(), ProcessBackActivity.class);
                        startActivity(it);
                        break;
                    case "知识库":
                        EventBus.getDefault().post(new GoGuideEvent());
                        break;
                    case "维保缺陷":
                        it = new Intent(getActivity(), DefectManageActivity.class);
                        startActivity(it);
                        break;
                    case "巡检轨迹":
                        it = new Intent(getActivity(), TrajectoryActivity.class);
                        startActivity(it);
                        break;
                }
            }
        });


    }

    private void initBanner() {
        //资源文件
        final List<Integer> images = new ArrayList<>();
        images.add(R.mipmap.ic_logo_1);
        //设置banner样式
        banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new BannerImageLoader());
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置图片集合
        banner.setImages(images);
        banner.start();
    }

    /**
     * 判断是否有未读消息
     */
    private void isHasMsg(){
        ApiService.unread()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onNext(ResponseData<Integer> retData) {
                        if (retData.retCode == 10000) {
                            if (retData.data > 0) {
                                iv_reddot.setVisibility(View.VISIBLE);
                            } else {
                                iv_reddot.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {

                    }
                });
    }

    /**
     * 获取首页内容
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getIndexAll(IndexAllEvent event) {
        showModule(event.indexBean);
    }



    /**
     * 显示功能模块
     * @param indexBean
     */
    private void showModule(IndexBean indexBean) {
//        rv_menu_list.setVisibility(View.GONE);
        ll_news_layout.setVisibility(View.GONE);
        ll_chart_layout.setVisibility(View.GONE);
        ll_knowledge_base_layout.setVisibility(View.GONE);
        ll_tools.setVisibility(View.GONE);
        ll_expert_layout.setVisibility(View.GONE);
        for (IndexBean.MenusBean menu : indexBean.menus) {
            switch (menu.value) {
//                case "NAVICATION"://菜单列表
//                    rv_menu_list.setVisibility(View.VISIBLE);
//                    initMenu(menu.childs);
//                    break;
                case "NEWS"://头条新闻
                    ll_news_layout.setVisibility(View.VISIBLE);
                    initHeadlines(indexBean.news);
                    break;
                case "SATISFACTION"://满意度
                    ll_chart_layout.setVisibility(View.VISIBLE);
                    initChart(indexBean.satisfaction);
                    break;
                case "KNOWLEDGE"://知识库
                    ll_knowledge_base_layout.setVisibility(View.VISIBLE);
                    initKnowledgeBase(indexBean.knowledge);
                    break;
                case "TOOLS"://小工具
                    ll_tools.setVisibility(View.VISIBLE);
                    break;
                case "EXPERT"://专家列表
                    ll_expert_layout.setVisibility(View.VISIBLE);
                    initExpert(indexBean.expert);
                    break;
            }
        }

    }

    /**
     * 知识库
     * @param knowledge
     */
    private void initKnowledgeBase(List<IndexBean.KnowledgeBean> knowledge) {
        if (knowledge == null || knowledge.isEmpty()) {
            ll_knowledge_base_layout.setVisibility(View.GONE);
            return;
        }

        KnowledgeBaseAdapter knowledgeBaseAdapter = new KnowledgeBaseAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        rv_knowledge_base.setLayoutManager(linearLayoutManager);
        rv_knowledge_base.setAdapter(knowledgeBaseAdapter);
        //添加ItemDecoration，item之间的间隔
        int leftRight = UIUtils.dip2px(11);
        int topBottom = UIUtils.dip2px(0);
        rv_knowledge_base.addItemDecoration(new SpacesItemDecoration(leftRight, topBottom));
        knowledgeBaseAdapter.setNewData(knowledge);
        knowledgeBaseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                IndexBean.KnowledgeBean item = (IndexBean.KnowledgeBean) adapter.getItem(position);
                Intent intent = new Intent(getContext(), KnowledgeInfoActivity.class);
                intent.putExtra("kId", item.id);
                startActivity(intent);
            }
        });

    }


    @OnClick({R.id.tv_more_news, R.id.tv_more_expert,R.id.iv_news,R.id.iv_scan,R.id.ll_search,R.id.tv_knowledge_more,R.id.ll_expert_btn,R.id.ll_inspection_btn,R.id.ll_guide_btn, R.id.ll_gadget_leaf, R.id.ll_gadget_form})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_more_news://更多头条新闻
                startActivity(new Intent(getContext(), HeadlineNewsActivity.class));
                break;
            case R.id.tv_more_expert://更多专家
                startActivity(new Intent(getContext(), ExpertListActivity.class));
                break;
            case R.id.iv_news://消息
                startActivity(new Intent(getContext(), MessageListActivity.class));
                break;
            case R.id.iv_scan://扫码
                RxPermissions permissions = new RxPermissions(getActivity());
                permissions.setLogging(true);
                permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    startActivityForResult(new Intent(getActivity(), QRcodeActivity.class),REQUEST_CODE);
                                } else {
                                    ToastUtils.show(getContext(), "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                }
                            }
                        });

                break;
            case R.id.ll_search://搜索知识库
                EventBus.getDefault().post(new GoGuideEvent());
                break;
            case R.id.tv_knowledge_more://更多知识库
                EventBus.getDefault().post(new GoGuideEvent());
                break;
            case R.id.ll_expert_btn://专家指导
                startActivity(new Intent(getContext(),ProblemFeedbackActivity.class));
                break;
            case R.id.ll_inspection_btn://巡检
                Intent it = new Intent(getContext(), IntellectInspectActivity.class);
                startActivity(it);
                break;
            case R.id.ll_guide_btn://操作向导
                startActivity(new Intent(getContext(), TipWizardListActivity.class));
                break;
            case R.id.ll_gadget_leaf://叶片排序
                startActivity(new Intent(getContext(), LeafSortActivity.class));
                break;
            case R.id.ll_gadget_form://三表找正
                startActivity(new Intent(getContext(), FormActivity.class));
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (REQUEST_CODE == requestCode && RESULT_OK == resultCode) {
            String value = data.getStringExtra("qr_code_key");
            Log.i("二维码", "onActivityResult: 返回值"+value);
            Intent intent = new Intent(getContext(), EquipmentInfoActivity.class);
            intent.putExtra("kks", value);
            startActivity(intent);


        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
